package cn.t.utils;


import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 随机数工具类
 */
public class RandomUtil {

    private static Random random;

    static {
        try {
            random = SecureRandom.getInstanceStrong();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static Random getRandomInstance() {
        return random;
    }

    public static String generateCode(int length, boolean charFlag) {
        StringBuilder val = new StringBuilder();
        for(int i = 0; i < length; ++i) {
            if (charFlag) {
                String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
                if ("char".equalsIgnoreCase(charOrNum)) {
                    int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
                    val.append((char) (choice + random.nextInt(26)));
                } else {
                    val.append(random.nextInt(10));
                }
            } else {
                val.append(random.nextInt(10));
            }
        }
        return val.toString().toLowerCase();
    }

    private RandomUtil() {}
}
